package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.FreezeDetailMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.model.domain.FreezeDetail;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.AdminCommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired(required = false)
    private FreezeDetailMapper freezeDetailMapper;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        Page<UserInfo> pageInfo = userInfoApi.findByPage(page, pagesize);
        return new PageResult(pageInfo.getCurrent(), pageInfo.getSize(), pageInfo.getTotal(),pageInfo.getRecords());
    }

    public UserInfo queryUserInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return userInfo;
    }

    public PageResult movementsList(Integer page, Integer pagesize, Long uid, Integer state) {
        PageResult pageResult = movementApi.findMovements(page, pagesize, uid, state);
        List<Movement> movementsList = (List<Movement>) pageResult.getItems();
        List<Long> userIds = CollUtil.getFieldValues(movementsList, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds);
        List<MovementsVo> voList = new ArrayList<>();
        for (Movement movement : movementsList) {
            UserInfo userInfo = userInfoMap.get(movement.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, movement);
            voList.add(vo);
        }
        pageResult.setItems(voList);
        return pageResult;
    }

    public PageResult videoList(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = videoApi.queryByUid(page, pagesize, uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();
        UserInfo userInfo = userInfoApi.findById(uid);
        List<VideoVo> voList = new ArrayList<>();
        for (Video video : videoList) {
            VideoVo vo = VideoVo.init(userInfo, video);
            voList.add(vo);
        }
        pageResult.setItems(voList);
        return pageResult;
    }

    //冻结用户
    @Transactional
    public Map<String, String> freeze(FreezeDetail freezeDetail) {
        // 补全参数
        freezeDetail.setOperationUserId(AdminHolder.getUserId());
        freezeDetail.setUpdated(new Date());
        freezeDetail.setCreated(new Date());
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //获得冻结天数
        Integer freezingTime = freezeDetail.getFreezingTime();
        int time;
        if (freezingTime == 1) {//3天   7天    永久
            time = 3;
        } else if (freezingTime == 2) {
            time = 7;
        } else {
            time = 36000;
        }

        Integer freezingRange = freezeDetail.getFreezingRange();
        //统一更改用户的状态为冻结
        Long userId = freezeDetail.getUserId();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setUserStatus("2");
        userInfo.setUpdated(new Date());
        userInfoApi.update(userInfo);
        //获取冻结原因
        String reason = freezeDetail.getReasonsForFreezing();
        if (freezingRange == 1) {//1为冻结登录   2为冻结发言    3为冻结发布动态
            operations.set(Constants.FreezeLogin_KEY + userId, reason, time, TimeUnit.DAYS);
        } else if (freezingRange == 2) {
            operations.set(Constants.FreezeComment_KEY + userId, reason, time, TimeUnit.DAYS);
        } else {
            operations.set(Constants.FreezeMovement_KEY + userId, reason, time, TimeUnit.DAYS);
        }
        //统一保存冻结记录, 方便日后追溯以及统一数据
        freezeDetailMapper.insert(freezeDetail);

        HashMap<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }
    @Transactional
    public Map<String, String> unfreeze(FreezeDetail freezeDetail) {
        //查出这条冻结的记录
        Long userId = freezeDetail.getUserId();
        FreezeDetail detail = freezeDetailMapper.selectLatest(userId);
        Integer freezingRange = detail.getFreezingRange();
        //把属性复制进去后更新
        detail.setUpdated(new Date());
        detail.setOperationUserId(AdminHolder.getUserId());
        detail.setReasonsForThawing(freezeDetail.getFrozenRemarks());
        freezeDetailMapper.updateById(detail);
        //改变用户的冻结状态
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        //删除redis中的记录
        if (freezingRange == 1) {
            redisTemplate.delete(Constants.FreezeLogin_KEY + userId);
        } else if (freezingRange == 2) {
            redisTemplate.delete(Constants.FreezeComment_KEY + userId);
        } else {
            redisTemplate.delete(Constants.FreezeMovement_KEY + userId);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }

}
